# encoding=utf-8
import os
import configparser
import xlrd
import openpyxl
import json
import random
import datetime
import requests
import time
import xlwt
from xlutils.copy import copy

from common.yaml_util import clear_yaml

base_dir = str(os.path.dirname(os.path.dirname(__file__)))
print(base_dir)
conf_path = base_dir + "/config/config.conf"
report_path = base_dir + "/report/allure_report"
report_raw_path = base_dir + "/report/allure_raw"
data_path = base_dir + "/data/"
img_path = base_dir + "/img/"
tests_path = base_dir + "/tests/"
cf = configparser.ConfigParser()  # configparser类来读取config文件
cf.read(conf_path, encoding='utf-8')



def get_json(path):
    with open(
            base_dir + path, "r",
            encoding="utf-8") as f:
        json_data = json.load(f)
        return json_data


def get_lines(path):
    with open(
            data_path+path, "r",
            encoding="utf-8") as f:
        lines = f.readlines()
        f.close()
        return lines

# 获取配置
def getconf(env, param):
    param = cf.get(env, param)
    return param


# 中台登录接口获取token
headerscms = {"Content-Type": "application/json;charset=UTF-8",
              "application": "cms_ry"}

headersbus = {"Content-Type": "application/json;charset=UTF-8",
              "application": "cms"}


# 大运营token
def cmslogin(env):
    base_url = getconf(env, "zhongtai_url")
    url = base_url + "buorg/v1/session/login"
    user = getconf(env, "cmsuser")
    password = getconf(env, "cmspass")
    data = {
        "account": user,
        "password": password
    }
    r = requests.post(url, json=data, headers=headerscms)
    token = r.json()['token']
    return token


# 商家后台token
def buslogin(env):
    base_url = getconf(env, "zhongtai_url")
    url = base_url + "buorg/v1/session/login"
    user = getconf(env, "bususer")
    password = getconf(env, "buspass")
    data = {
        "account": user,
        "password": password
    }
    r = requests.post(url, json=data, headers=headersbus)
    token = r.json()['token']
    return token



# 停车商家后台token（运营中心）
def caryylogin(env):
    base_url = getconf(env, "zhongtai_url")
    url = base_url + "buorg/v1/session/login"
    user = getconf(env, "caryyuser")
    password = getconf(env, "caryypass")
    data = {
        "account": user,
        "password": password
    }
    r = requests.post(url, json=data, headers=headersbus)
    token = r.json()['token']
    return token


# 读excel获取data请求数据
def getdata(env, game, rowx):
    # rowx表示在excel中的行数
    activityId = getconf(env, game)
    file_path = data_path + activityId + ".xlsx"
    book = xlrd.open_workbook(file_path)
    sheet = book.sheet_by_index(0)
    data = sheet.row_values(rowx)[2]
    return json.loads(data)


# 读excel获取data请求数据
def hd_getdata(path, row):
    # rowx表示在excel中的行数
    file_path = data_path + path + ".xlsx"
    book = xlrd.open_workbook(file_path)
    sheet = book.sheet_by_index(0)
    openId = sheet.row_values(row)[0]
    userId = sheet.row_values(row)[1]
    return openId, userId


# 读excel获取data请求数据
def gettestdata():
    # rowx表示在excel中的行数
    file_path = data_path + + "test.xlsx"
    book = xlrd.open_workbook(file_path)
    sheet = book.sheet_by_index(0)
    data = sheet.row_values(1)[2]
    return json.loads(data)


# 向excel写数据
def writedata(value):
    path = tests_path + 'Excel_test.xls'
    # value=['test','test','test','test','test','test']
    # workbook = xlwt.Workbook(encoding='utf-8')
    index = len(value)  # 获取需要写入数据的行数
    workbook = xlrd.open_workbook(path, 'utf-8')  # 打开工作簿
    sheets = workbook.sheet_names()  # 获取工作簿中的所有表格
    worksheet = workbook.sheet_by_name(sheets[0])  # 获取工作簿中所有表格中的的第一个表格
    rows_old = worksheet.nrows  # 获取表格中已存在的数据的行数
    new_workbook = copy(workbook)  # 将xlrd对象拷贝转化为xlwt对象
    new_worksheet = new_workbook.get_sheet(0)  # 获取转化后工作簿中的第一个表格
    for i in range(0, index):
        new_worksheet.write(1, i, value[i])  # 追加写入数据，注意是从i+rows_old行开始写入
        print("写入数据", value[i])
    new_workbook.save(path)  # 保存工作簿
    print("xls格式表格【追加】写入数据成功！")


# 获取用例数据
def getCaseData(env, fileName, rowx):
    file_path = data_path + fileName + ".xlsx"
    book = xlrd.open_workbook(file_path)
    sheet = book.sheet_by_name(env)
    data = sheet.row_values(rowx)[1]
    return json.loads(data)


# 按照行读取表格数据
def Excel(path):
    workbook = xlrd.open_workbook(path)
    allSheetName = workbook.sheet_names()
    sheet1name = workbook.sheet_names()[0]
    sheet1_conntent2 = workbook.sheet_by_index(0)
    # print(sheet1_conntent2.nrows)
    data1 = []
    for a in range(1, sheet1_conntent2.nrows):
        data1.append(sheet1_conntent2.row_values(a))
    # print(data1)
    return data1


# 获取指定用户token
def getToken(env):
    base_url = getconf(env, "data_url")
    url = base_url + "buorg/v1/session/login"
    user = getconf(env, "user1")
    password = getconf(env, "passwd1")
    data = {
        "account": user,
        "password": password
    }
    # print (data)
    r = requests.post(url, json=data, headers=headersbus)
    token = r.json()['token']
    # print(token)
    return token


# 获取指定用户token
def getToken_b(env):
    base_url = getconf(env, "data_url")
    url = base_url + "buorg/v1/session/login"
    user = getconf(env, "user2")
    password = getconf(env, "passwd2")
    data = {
        "account": user,
        "password": password
    }
    # print (data)
    r = requests.post(url, json=data, headers=headersbus)
    token = r.json()['token']
    # print(token)
    return token


# 更新白名单表
def updatepwl(column, shuju):
    file_path = data_path + "pwl.xlsx"
    wb = openpyxl.load_workbook(file_path)
    sheet = wb[wb.active.title]
    sheet.cell(row=2, column=column, value=shuju)
    wb.save(file_path)


# 更新excel文件
def updatefile(row, column, shuju, filename):
    file_path = data_path + filename + ".xlsx"
    wb = openpyxl.load_workbook(file_path)
    sheet = wb[wb.active.title]
    sheet.cell(row=row, column=column, value=shuju)
    wb.save(file_path)


# 获取随机openid
def getopenId():
    openId = (''.join(random.sample(
        ['z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e',
         'd', 'c', 'b', 'a', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
         'Z', 'Y', 'X', 'W', 'V', 'U', 'T', 'S', 'R', 'Q', 'P', 'O', 'N', 'M', 'I', 'K', 'J', 'I', 'H', 'G', 'F', 'E',
         'D', 'C', 'B', 'A', '-', '_', ], 28)))
    return openId


# 获取随机手机号
def getphone():
    prelist = ["13", "14", "15", "16", "17", "18", "19"]
    return random.choice(prelist) + "".join(random.choice("0123456789") for i in range(9))


# 返回当前时间+n秒后的时间
def gettime(num):
    now = datetime.datetime.now()
    delta = datetime.timedelta(seconds=num)
    deltatime = now + delta
    if num not in (-1, -2):
        Time = deltatime.strftime('%Y-%m-%d %H:%M:%S')
    elif num == -1:
        Time = deltatime.strftime('%Y-%m')
    elif num == -2:
        Time = deltatime.strftime('%Y-%m-%d')
    return Time


# 获取随机appid
def getappid():
    pre = "wx"
    return pre + "".join(random.choice("0123456789abcde") for i in range(16))


# 获取随机生日
def getbirth():
    a1 = (1976, 1, 1, 0, 0, 0, 0, 0, 0)  # 设置开始日期时间元组（1976-01-01 00：00：00）
    a2 = (2020, 12, 31, 23, 59, 59, 0, 0, 0)  # 设置结束日期时间元组（1990-12-31 23：59：59）
    start = time.mktime(a1)  # 生成开始时间戳
    end = time.mktime(a2)  # 生成结束时间戳
    t = random.randint(start, end)  # 在开始和结束时间戳中随机取出一个
    date_touple = time.localtime(t)  # 将时间戳生成时间元组
    date = time.strftime("%Y-%m-%d", date_touple)  # 将时间元组转成格式化字符串（1976-05-21）
    # print(date)
    return date


# 获取随机url链接
def geturl():
    pre = "http://www."
    end = ".com"
    return pre + "".join(random.choice("0123456789abcdefghijklmnopqrstuvwxyz") for i in range(9)) + end


# 计算环比
def comp(a, b):
    if len(a) > 0:
        if len(b) > 0 and int(b) > 0:
            return str('%.2f' % ((int(a) / int(b) - 1) * 100)) + '%'
        else:
            return '--'
    else:
        return '--'


# ======================契望成相关======================

def clear_supplier_cookie():
    """多个供应商cookie批量清除"""
    print("清除文件开始===========>")
    phone = ["13000000000", "16000000001", "13524982440"]
    try:
        for p in phone:
            clear_yaml("/data/supplier_" + p + ".yaml")
    except Exception as e:
        print(e)


if __name__ == "__main__":
    # data = gettime(-1)
    # data=updatepwl(4,"18721428902")
    # data=getbirth()
    # data=geturl()
    # data=getconf("test","zhongtai_url")
    # data=getopenId()
    # data=buslogin("v4")
    #  writedata()
    # print(data)
    # getToken('test')
    # a = comp('2', '2')
    #print(time.mktime(0))
    print("测试")